package com.th.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.th.common.domain.UsBankCards;
import com.th.common.enums.BankType;
import com.th.common.enums.BankcardType;
import com.th.common.response.CommonResponse;
import com.th.common.utils.DateUtils;
import com.th.config.web.BaseController;
import com.th.service.UsBankCardsService;
import com.th.service.UsUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@RestController
@Api(tags = "用户银行绑定接口")
@RequestMapping("/api/bankcard")
public class UsBankInfoController extends BaseController {
    @Resource
    private UsBankCardsService usBankCardsService;

    @Resource
    private UsUserService userService;
    /***
     * 用户银行卡绑定
     * @param token
     * @param bankType
     * @param cardId
     * @param bankcardType
     * @param phone
     * @return
     */
    @ApiOperation("用户银行卡绑定")
    @PostMapping("/bindBankcard")
    public CommonResponse<String> bindBankcard(@RequestHeader("token") String token,@RequestParam("bankType") Integer bankType,@RequestParam("cardId")String cardId,@RequestParam("bankcardType")Integer bankcardType,@RequestParam("phone")String phone){
        Long userId=userService.getCurrentUserId();
        //绑定之前先查询是否存在！
        LambdaQueryWrapper<UsBankCards> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        UsBankCards usBankCard=usBankCardsService.getOne(lambdaQueryWrapper.eq(UsBankCards::getCardId,cardId));
        if(usBankCard!=null){
            UsBankCards usBankCard1=usBankCardsService.getOne(lambdaQueryWrapper.eq(UsBankCards::getUserId,userId));
            if(usBankCard1!=null){
                return CommonResponse.error(9000,"此卡已经绑定！");
            }
            return CommonResponse.error(9000,"此卡已被其他用户绑定！");
        }
        Date now= DateUtils.getNowDate();
        UsBankCards usBankCards=new UsBankCards();
        usBankCards.setUserId(userId);
        usBankCards.setBankType(BankType.of(bankType).getName());
        usBankCards.setBankcardType(BankcardType.of(bankcardType).getName());
        usBankCards.setCardId(cardId);
        usBankCards.setPhone(phone);
        usBankCards.setCreateTime(now);
        usBankCardsService.save(usBankCards);
        return CommonResponse.success("绑定成功!");
    }

    @ApiOperation("/用户银行绑定查询")
    @GetMapping("/getAll")
    public List<UsBankCards> getAll(){
      return usBankCardsService.list();
    }
}
